package com.rc.scripting.plugin;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 
 * @author juntao.qiu@gmail.com
 * @date 2010-5-13
 */
public class SimplePluginManager implements PluginManager {
	//linked hash map to store the plugin
	private LinkedHashMap<String, Plugin> pluginMap;
	
	//max size of the manager(which is kind of a container)
	private static final int maxPlugins = 100;
	
	private static SimplePluginManager instance;
	
	/*
	 * using the LRU algorithm to maintain the map
	 */
	private SimplePluginManager(final int num){
		pluginMap = new LinkedHashMap<String, Plugin>(num, 1, true){
			private static final long serialVersionUID = 749834145044922744L;
			protected boolean removeEldestEntry(
					Map.Entry<String, Plugin> eldest) {
				return size() > num;
			}
		};
	}
	
	public static SimplePluginManager getInstance(){
		if(instance == null){
			instance = new SimplePluginManager();
		}
		return instance;
	}
	
	public SimplePluginManager(){
		this(maxPlugins);
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.rc.json.plugin.PluginManager#getPlugin(java.lang.String)
	 */
	public Plugin getPlugin(String name) {
		return pluginMap.get(name);
	}

	/*
	 * (non-Javadoc)
	 * @see com.rc.json.plugin.PluginManager#getPluginCount()
	 */
	public int getPluginCount() {
		return pluginMap.size();
	}

	/*
	 * (non-Javadoc)
	 * @see com.rc.json.plugin.PluginManager#install(com.rc.json.plugin.Plugin)
	 */
	public void install(Plugin plugin) {
		pluginMap.put(plugin.getName(), plugin);
	}

	/*
	 * (non-Javadoc)
	 * @see com.rc.json.plugin.PluginManager#uninstall(com.rc.json.plugin.Plugin)
	 */
	public Plugin uninstall(Plugin plugin) {
		return pluginMap.remove(plugin.getName());
	}

}
